package com.zzj.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class IPUtil {

    @Resource
    private HttpUtil httpUtil;


    public String getProvinceByIP(String ip) {
        Map<String, String> headerMap =new ConcurrentHashMap<>();
        String  str = (String) httpUtil.get("https://apis.map.qq.com/ws/location/v1/ip?key=OGTBZ-GUCKQ-NS45J-46TM5-EZ5XF-TQFF7&ip="+ ip, headerMap, String.class);
        JSONObject jsonObject = JSON.parseObject(str);
        if(jsonObject.getInteger("status")==375){
            return "本地";
        }
        if(jsonObject.getInteger("status")!=0){
            return "属地查询失败";
        }
        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject ad_info = result.getJSONObject("ad_info");
        return ad_info.getString("province");
    }

    public String getIP(HttpServletRequest request){
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }
}